//
//  ZZCLawController.m
//  ZZC-Finance
//
//  Created by mac on 2017/5/21.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "ZZCLawController.h"
#import "ZZCScanController.h"
#import "ZZCLawView.h"
#import <AssetsLibrary/AssetsLibrary.h>

@interface ZZCLawController ()<UITextFieldDelegate,UIScrollViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (strong, nonatomic) ZZCLawView *lawView;
@property (strong, nonatomic) ZZCMenuView *menuViewA;
@property (strong, nonatomic) ZZCMenuView *menuViewB;
@property (strong, nonatomic) ZZCMenuView *menuViewC;
@property (copy,   nonatomic) NSString *name;

@property (strong, nonatomic) UIButton *btn1;
@property (strong, nonatomic) UIButton *btn2;
@property (copy,   nonatomic) NSString *imgUrl;
@property (retain, nonatomic) NSURL *uurl;

@property (strong, nonatomic) UILabel *stateLabel;
@property (strong, nonatomic) UIButton *bbtn;
@property (nonatomic, strong) CityChoose *cityChoose;    /** 城市选择 */
@property (copy, nonatomic) NSString *province;
@property (copy, nonatomic) NSString *city;
@property (copy, nonatomic) NSString *area;

@property (nonatomic, assign) NSInteger sexType;
@property (nonatomic, assign) NSInteger photoType;
@property (nonatomic,   copy) NSString *imageUrl_1;//身份证正面
@property (nonatomic,   copy) NSString *imageUrl_2;//身份证背面
@property (nonatomic,   copy) NSString *imageUrl_3;//资质证明
@property (nonatomic,   copy) NSString *imageUrl_4;//人脸
@end

@implementation ZZCLawController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"申请法律专家";
//    _stateLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, ZZCScreenH*0.9f, ZZCScreenW, ZZCScreenH*0.175f)];
//    _stateLabel.backgroundColor = [UIColor grayColor];
//    [self.lawView.bgScrollView addSubview:_stateLabel];
//    _stateLabel.hidden = YES;
    //状态标签
    UIView *subviews  = [self.lawView viewWithTag:1145];
    subviews.hidden = YES;
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.lawView];
    _sexType = 1;
    [_lawView.sexBtn addTarget:self action:@selector(sexBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.lawView.rankBtn.tag = 1;
    [self.lawView.rankBtn addTarget:self action:@selector(rankBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.lawView.gradeBtn.tag = 2;
    [self.lawView.gradeBtn addTarget:self action:@selector(gradeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.lawView.regionBtn.tag = 3;
    [self.lawView.regionBtn addTarget:self action:@selector(regionBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.lawView.bgScrollView.delegate = self;
    self.lawView.bgScrollView.bounces = NO;
    
    NSArray *arr = @[@"省级",@"市级",@"县级"];
    self.menuViewA = [[ZZCMenuView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.lawView.rankView.frame), ZZCScreenW, 132) contentArray:arr];
    __weak typeof (self) weakself = self;
    self.menuViewA.block = ^(BOOL isSeletct ,NSString *title){
        weakself.menuViewA.hidden = YES;
        if (title.length != 0) {
            [weakself.lawView.rankBtn setTitle:title forState:UIControlStateNormal];
        }
    };
    
    NSMutableArray *arr1 = [NSMutableArray new];
    for (int i = 1; i <= 80; i ++) {
        [arr1 addObject:[NSString stringWithFormat:@"%d",i]];
    }

    self.menuViewB = [[ZZCMenuView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.lawView.gradeView.frame), ZZCScreenW, 132) contentArray:arr1];

    self.menuViewB.block = ^(BOOL isSeletct ,NSString *title){
        weakself.menuViewB.hidden = YES;
        if (title.length != 0) {
            [weakself.lawView.gradeBtn setTitle:title forState:UIControlStateNormal];
        }
    };
    
    NSArray *arr2 = @[@"等级7",@"等级8",@"等级9",@"等级10",@"等级11",@"等级12"];
    self.menuViewC = [[ZZCMenuView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.lawView.regionView.frame), ZZCScreenW, 132) contentArray:arr2];
    
    self.menuViewC.block = ^(BOOL isSeletct ,NSString *title){
        weakself.menuViewC.hidden = YES;
        if (title.length != 0) {
            [weakself.lawView.regionBtn setTitle:title forState:UIControlStateNormal];
        }
    };
     self.menuViewA.hidden = YES;
     self.menuViewB.hidden = YES;
     self.menuViewC.hidden = YES;
    [self.lawView addSubview:self.menuViewA];
    self.menuViewA.y = self.lawView.rankView.y+44;
    [self.lawView addSubview:self.menuViewB];
    self.menuViewB.y = self.lawView.gradeView.y+44;
    [self.lawView addSubview:self.menuViewC];
    self.menuViewC.y = self.lawView.regionView.y+44;
    
    [self bottomBtn];
    
    [_lawView.idCardBtn1 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_lawView.idCardBtn2 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_lawView.proveBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

}
- (void)btnClick:(UIButton *)sender {
    if (sender.tag == 991) {
        _photoType = 1;
    } else if (sender.tag == 992) {
        _photoType = 2;
    } else if (sender.tag == 993) {
        _photoType = 3;
    }
    [self userEvent];
}
//调用相机
- (void)userEvent {
    [self cameraBtnDidClick];
}

-(void)cameraBtnDidClick{
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    alertController.view.tintColor = [UIColor colorWithHex:0xEB6927];
    UIAlertAction * photo = [UIAlertAction actionWithTitle:@"拍照" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self openPhotoWithType:1];
    }];
    
    UIAlertAction * choice = [UIAlertAction actionWithTitle:@"相册选择" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self openPhotoWithType:0];
    }];
    
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style: UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    
    [alertController addAction:photo];
    [alertController addAction:choice];
    [alertController addAction:cancel];
    [self showDetailViewController:alertController sender:nil];
    
}

#pragma mark - 相册 相机
- (void)openPhotoWithType:(int)type
{
    if ([self getMediaTypeVideo]) {  //获取相机权限
        UIImagePickerControllerSourceType sourceType = type;
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
        picker.delegate = self;
        picker.allowsEditing = YES;//设置可编辑
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];//进入照相界面
    }else{
        [[[UIAlertView alloc] initWithTitle:nil
                                    message:@"请设置使用照片。\n请启用照片-设置/隐私/照片"
                                   delegate:nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil, nil] show];
        
        NSLog(@"相机受限");
    }
}

#pragma mark 判断摄像头权限
-(bool)getMediaTypeVideo
{
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    
    if(author == ALAuthorizationStatusRestricted){// 受限制 家长权限之类的
        
        return NO;
        
    } else if(author == ALAuthorizationStatusDenied){// 已经拒绝的
        
        [[[UIAlertView alloc] initWithTitle:nil
                                    message:@"请设置使用照片。\n请启用照片-设置/隐私/照片"
                                   delegate:nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil, nil] show];
        return NO;
    } else if(author == ALAuthorizationStatusAuthorized){// 已允许的
        
        return YES;
        
    } else if(author == ALAuthorizationStatusNotDetermined){// 还没决定的
        
        return YES;
    } else {
        
        return NO;
    }
}
#pragma mark - imagePicker delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *img = [self scaleToSize:[info objectForKey:@"UIImagePickerControllerEditedImage"] size:CGSizeMake(300, 300)];
    ZZCLog(@"%@",img);
    [self uploadImage:img];
    
}
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    [img drawInRect:CGRectMake(0,0, size.width, size.height)];
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}


#pragma mark - 上传图片
- (void)uploadImage:(UIImage *)img {
    NSString *token = ZZCNSUserDefaults(@"token");
    NSDictionary *param = @{@"token":token,@"type":@(2)};
    [[ZZCRequest sharedNetworkTools] uploadWithURL:ZZCURL_API_UPLOAD params:param formBoundary:img success:^(NSDictionary * _Nonnull data) {
        ZZCLog(@"%@",data);
        self.imgUrl = data[@"data"][@"url"];
        _uurl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ZZCURL_API,_imgUrl]];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updetaMeInfo" object:self];
        [self newnewIMG];
        if (_photoType == 4) {
            [self putIn];
        }
    } fail:^(NSError * _Nonnull error, NSString * _Nonnull msg, NSDictionary * _Nonnull data) {
        ZZCLog(@"%@",error);
    }];
}
- (void)newnewIMG {
    if (_photoType == 1) {
        [self.lawView.idCard1 sd_setImageWithURL:_uurl placeholderImage:[UIImage imageNamed:@"1.jpeg"]];
        _imageUrl_1 = _imgUrl;
    } else if (_photoType == 2) {
        [self.lawView.idCard2 sd_setImageWithURL:_uurl placeholderImage:[UIImage imageNamed:@"1.jpeg"]];
        _imageUrl_2 = _imgUrl;
    } else if (_photoType == 3) {
        [self.lawView.proveView sd_setImageWithURL:_uurl placeholderImage:[UIImage imageNamed:@"1.jpeg"]];
        _imageUrl_3 = _imgUrl;
    } else if (_photoType == 4) {
        NSLog(@"safsfdasdfsdf");
        _imageUrl_4 = _imgUrl;
        NSLog(@"##################%@",_imageUrl_4);
    }
}
#pragma mark - 提交申请
- (void)putIn {
    ZZCLog(@"提交申请");
    //    判断身份证
    if (![ZZCUtils checkUserIdCard:_lawView.cardTextField.text]) {
        NSLog(@"身份证格式错误");
        [SVProgressHUD showInfoWithStatus:@"请输入正确身份证号码!"];
        return;
    }

    if (_lawView.nameTextField == nil
        ||_lawView.BRbirthFLD.text == nil
//        ||_lawView.birthdayTextField.text == nil
        ||_lawView.phoneTextField.text == nil
        ||_lawView.cardTextField.text == nil
        ||_lawView.mailboxTextField.text == nil
        ||_imageUrl_1 == nil
        ||_imageUrl_2 == nil
        ||_imageUrl_3 == nil
        ||_province == nil
        ||_city == nil
        ||_area == nil) {
        [SVProgressHUD showInfoWithStatus:@"请填写申请信息"];
        return;
    }

    NSString *token = ZZCNSUserDefaults(@"token");
    NSDate *currentDate = [NSDate date];
    NSString *timeStr = [NSString stringWithFormat:@"%ld",(long)[currentDate timeIntervalSince1970]];
    NSDictionary *dict = @{
                           @"token":token,
                           @"type":@(1),
                           @"username":_lawView.nameTextField.text,
                           @"sex":@(_sexType),
                           @"birthday":_lawView.BRbirthFLD.text,
                           @"phone":_lawView.phoneTextField.text,
                           @"id_card":_lawView.cardTextField.text,
                           @"id_img_front":_imageUrl_1,
                           @"id_img_bace":_imageUrl_2,
                           @"leave":@(1),
                           @"word_age":@(1),
                           @"img_url":_imageUrl_3,
                           @"province":_province,
                           @"city":_city,
                           @"district":_area,
                           @"email":_lawView.mailboxTextField.text,
                           @"face_url":_imageUrl_4
                           };
    NSString *sign = [ZZCRequest getSignWithDict:dict];
    sign = [NSString md5:[sign lowercaseString]];
    NSDictionary *param = @{@"timestamp":timeStr,@"sign":sign,
                            @"token":token,
                            @"type":@(1),
                            @"username":_lawView.nameTextField.text,
                            @"sex":@(_sexType),
                            @"birthday":_lawView.BRbirthFLD.text,
                            @"phone":_lawView.phoneTextField.text,
                            @"id_card":_lawView.cardTextField.text,
                            @"id_img_front":_imageUrl_1,
                            @"id_img_bace":_imageUrl_2,
                            @"leave":@(1),
                            @"word_age":@(1),
                            @"img_url":_imageUrl_3,
                            @"province":_province,
                            @"city":_city,
                            @"district":_area,
                            @"email":_lawView.mailboxTextField.text,
                            @"face_url":_imageUrl_4
                            };
    [[ZZCRequest sharedNetworkTools] POST:ZZCURL_API_LAWYER parameters:param finished:^(id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            NSLog(@"@@@@@@@@@@@&&&&&&&&&&&&%@",responseObject);
            if ([responseObject[@"code"] isEqual:@(200)]) {
                _lawView.statusLabel.text = responseObject[@"msg"];
//                            _stateLabel.hidden = NO;
                UIView *subviews  = [self.lawView viewWithTag:1145];
                subviews.hidden = NO;
                
                UIButton *button = [self.view viewWithTag:1119];
                button.hidden = YES;
            } else if([responseObject[@"code"] isEqual:@(400)]){
                [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
            }

        } else {
            
            NSLog(@"%@",error);
            

//            [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
        }
    }];
}
- (void)bottomBtn {
    _bbtn = [[UIButton alloc] initWithFrame:CGRectMake(0, ZZCScreenH-113, ZZCScreenW, 49)];
    _bbtn.backgroundColor = [UIColor colorWithHex:0xEA6E25];
    [_bbtn setTitle:@"下一步" forState:0];
    [_bbtn addTarget:self action:@selector(shootFaceAction) forControlEvents:UIControlEventTouchUpInside];
    _bbtn.titleLabel.font = FONT(19);
    [_bbtn setTag:1119];
    [self.view addSubview:_bbtn];
}
// - (void)nextClick {
//    ZZCLog(@"下一步");
//    ZZCScanController *scan = [ZZCScanController new];
//    [self.navigationController pushViewController:scan animated:YES];
//    
//}
- (void) shootFaceAction {
    _photoType = 4;
    
    [self openPhotoWithType:1];
    [SVProgressHUD showInfoWithStatus:@"请拍摄本人正脸"];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    self.menuViewA.y = self.lawView.rankView.y+44 - scrollView.contentOffset.y;
    self.menuViewB.y = self.lawView.gradeView.y+44 - scrollView.contentOffset.y;
    self.menuViewC.y = self.lawView.regionView.y+44 - scrollView.contentOffset.y;
}


- (void)rankBtnClick {
    [self.view endEditing:YES];
    self.menuViewA.hidden = !self.menuViewA.hidden;
    self.menuViewB.hidden = YES;
    self.menuViewC.hidden = YES;
}
- (void)gradeBtnClick {
    [self.view endEditing:YES];
    self.menuViewB.hidden = !self.menuViewB.hidden;
    self.menuViewA.hidden = YES;
    self.menuViewC.hidden = YES;

}
- (void)regionBtnClick {
//    [self.view endEditing:YES];
//    self.menuViewC.hidden = !self.menuViewC.hidden;
//    self.menuViewA.hidden = YES;
//    self.menuViewB.hidden = YES;
    self.cityChoose = [[CityChoose alloc] init];
    __weak typeof(self) weakSelf = self;
    self.cityChoose.config = ^(NSString *province, NSString *city, NSString *town){
        weakSelf.lawView.regionLabel.text = [NSString stringWithFormat:@"%@-%@-%@",province,city,town];
        weakSelf.province = province;
        weakSelf.city = city;
        weakSelf.area = town;
    };
    [self.view addSubview:self.cityChoose];

}

#pragma mark - SexBtnAction
- (void)sexBtnAction:(RadioButton *)sender {
    if ([sender.titleLabel.text isEqualToString:@"男"]) {
        _sexType = 1;
    } else {
        _sexType = 2;
    }
}
#pragma mark - 值接收
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    self.menuViewA.hidden = YES;
    self.menuViewB.hidden = YES;
    self.menuViewC.hidden = YES;
    __weak typeof(self) weakSelf = self;
    weakSelf.lawView.BRbirthFLD.tapAcitonBlock = ^{
        [BRDatePickerView showDatePickerWithTitle:@"出生日期" dateType:UIDatePickerModeDate defaultSelValue:weakSelf.lawView.BRbirthFLD.text minDateStr:@"" maxDateStr:[NSDate currentDateString] isAutoSelect:YES resultBlock:^(NSString *selectValue) {
            weakSelf.lawView.BRbirthFLD.text = selectValue;
        }];
    };
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField == self.lawView.nameTextField) {
//名字值接收,自己创建属性接收需要的值
        self.name = textField.text;
        ZZCLog(@"%@",textField.text);
    }else if (textField == self.lawView.sexTextField){
        ZZCLog(@"%@",textField.text);
    }else if (textField == self.lawView.BRbirthFLD){
        ZZCLog(@"%@",textField.text);
    }else if (textField == self.lawView.phoneTextField){
        textField.keyboardType = UIKeyboardTypeNumberPad;
        ZZCLog(@"%@",textField.text);
    }else if (textField == self.lawView.cardTextField){
        textField.keyboardType = UIKeyboardTypeNumberPad;
        ZZCLog(@"%@",textField.text);
    }else if (textField == self.lawView.mailboxTextField){
        ZZCLog(@"%@",textField.text);
    }
    
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.lawView.phoneTextField) {
        //用来做长度限制；
        if (range.location>=11) {
            return NO;
        }
    }
    if (textField == self.lawView.cardTextField) {
        //用来做长度限制；
        if (range.location>=18) {
            return NO;
        }
    }
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.tag == 96457) {
//        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}

- (ZZCLawView *)lawView {
    if (_lawView == nil) {
        _lawView = [ZZCLawView lawView];
        _lawView.frame = CGRectMake(0, 0, ZZCScreenW, ZZCScreenH);
        _lawView.nameTextField.delegate = self;
        _lawView.sexTextField.delegate = self;
        _lawView.BRbirthFLD.delegate = self;
        _lawView.phoneTextField.delegate = self;
        _lawView.cardTextField.delegate = self;
        _lawView.mailboxTextField.delegate = self;

    }
    return _lawView;
}

@end
